package com.ag.utils;

import java.io.IOException;
import java.lang.reflect.Type;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

public class StringConvertJSONArray2Serializer implements ObjectSerializer {

	@Override
	public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
			throws IOException {
		SerializeWriter out = serializer.out;
		
		String string = (String) object;
		
		JSONArray array = JSON.parseArray(string);
		if(array == null) {
			out.writeNull();
		} else {
			array.forEach(action -> {
				Object v2 = action;
				if(v2 != null && v2 instanceof String) {
					String vStr2 = (String) v2;
					if(StringUtils.startsWith(vStr2, "{")) {
						JSONObject json = JSON.parseObject(vStr2);
						
						for(String key : json.keySet()) {
							Object v = json.get(key);
							if(v != null && v instanceof String) {
								String vStr = (String) v;
								if(StringUtils.startsWith(vStr, "{")) {
									json.put(key, JSON.parseObject(vStr));
								} else if(StringUtils.startsWith(vStr, "[")) {
									json.put(key, JSON.parseArray(vStr));
								}
							}
						}
						
						array.remove(action);
						array.add(json);
						
					} else if(StringUtils.startsWith(vStr2, "[")) {
						array.remove(action);
						array.add(JSON.parseArray(vStr2));
					}
				}
			});
			
			
			out.write(array.toJSONString());
		}
	}

}
